package com.tzstcl.framework.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Redis分布式锁
 */
@Service
public class RedisLockService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 上锁
     * @param key 锁key
     * @param value 锁value
     * @return boolean
     */
    public boolean enLock(String key, String value) {
        return enLock(key, value, Long.valueOf(5L));
    }

    /**
     * 上锁(带超时)
     * @param key 锁key
     * @param value 锁value
     * @param lockTime 锁定时间(超时秒数)
     * @return boolean
     */
    public boolean enLock(String key, String value, long lockTime) {
        boolean result = false;
        if (stringRedisTemplate.opsForValue().setIfAbsent(key, value, lockTime, TimeUnit.SECONDS)) {
            result = true;
        }
        return result;
    }

    /**
     * 下锁
     * @param key 锁key
     * @param value 锁value
     * @return boolean
     */
    public boolean deLock(String key, String value) {
        boolean result = false;
        String currentValue = stringRedisTemplate.opsForValue().get(key);
        if (currentValue == null) {
            result = true;
        }else if(currentValue.equals(value)){
            if(stringRedisTemplate.delete(key)){
                result = true;
            }
        }
        return result;
    }

}
